package com.rzico.sbl.ui.manager

import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.widget.doOnTextChanged
import com.jeremyliao.liveeventbus.utils.observe
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityOrderBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.OrderFooter
import com.rzico.sbl.model.OrderGoods
import com.rzico.sbl.model.OrderHeader
import com.rzico.sbl.other.showPriceDialog
import com.rzico.sbl.other.userRole
import com.rzico.sbl.ui.order.*
import com.rzico.sbl.viewmodel.OrderViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.hideSoftInput
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.glideExt.loadImage
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.setEmptyImage
import com.xinnuo.common_ui.utils.showHintDialog
import com.xinnuo.common_ui.utils.subscribeBySuccess
import com.xinnuo.slimadapter.SlimAdapter

class PickupOrderActivity : BaseActivity(R.layout.activity_order) {

    private val mBinding by lazy { ActivityOrderBinding.bind(getRootView()) }
    private var mKeyWord = ""

    override fun getViewModel() = get<OrderViewModel>()

    override fun initData() {
        setToolbarVisibility(isVisible = false)

        initLayout()
        initSearch()

        mBinding.apply {
            orderTab.gone()
            orderWarnFl.gone()
        }

        mBinding
            .listLayout
            .swipeRefresh
            .isRefreshing = true

        getData(pageNum)
    }

    private fun initLayout() {
        mBinding
            .listLayout
            .apply {
                emptyLayout.also {
                    it.emptyImg.setEmptyImage(
                        resId = R.mipmap.icon_order_no,
                        dpSize = 100f
                    )
                    it.emptyHint.text = "暂无相关订单信息！"
                }

                recycleList.also { layout ->
                    layout.loadLinear(
                        refresh = swipeRefresh,
                        onRefresh = { getData(0) },
                        onLoad = {
                            isLoadingMore
                                .conditionFalse {
                                    isLoadingMore = true
                                    getData(pageNum)
                                }
                        }
                    )

                    mAdapter = SlimAdapter.creator()
                        .register<OrderHeader>(R.layout.item_order_list_title) { jector, bean, index ->
                            jector.apply {
                                text(R.id.item_order_time, bean.hint + bean.time)
                                text(R.id.item_order_status, bean.status_hint)

                                visibility(
                                    R.id.item_order_divider,
                                    visibleValue { index == 0 }
                                )

                                clicked {
                                    startActivityEx<OrderDetailActivity>(
                                        "orderSn" to bean.orderSN,
                                        "shippingSn" to bean.shippingSn,
                                        "index" to bean.position
                                    )
                                }
                            }
                        }
                        .register<OrderGoods>(R.layout.item_order_list_content) { jector, bean, _ ->
                            jector.apply {
                                text(R.id.item_order_name, bean.name)
                                text(R.id.item_order_type, "规格：${bean.spec.orEmpty()}")
                                text(R.id.item_order_price, "单价：${bean.price.formatDecimal()}元")
                                text(R.id.item_order_num, "x${bean.quantity}")

                                with<ImageView>(R.id.item_order_img) {
                                    it.loadImage(bean.thumbnail)
                                }

                                with<ImageView>(R.id.item_order_img_type) {
                                    when (bean.methodDescr) {
                                        "offline" -> {
                                            it.visible()
                                            it.setImageResource(R.mipmap.icon_order03)
                                        }

                                        "eleme", "elemengc" -> {
                                            it.visible()
                                            it.setImageResource(R.mipmap.icon_order04)
                                        }

                                        "meituan" -> {
                                            it.visible()
                                            it.setImageResource(R.mipmap.icon_order05)
                                        }

                                        "nongfu" -> {
                                            it.visible()
                                            it.setImageResource(R.mipmap.icon_order06)
                                        }

                                        "jd" -> {
                                            it.visible()
                                            it.setImageResource(R.mipmap.icon_order10)
                                        }

                                        "taobao" -> {
                                            it.visible()
                                            it.setImageResource(R.mipmap.icon_order11)
                                        }

                                        "pinduoduo" -> {
                                            it.visible()
                                            it.setImageResource(R.mipmap.icon_order12)
                                        }

                                        "dummy" -> {
                                            it.visible()
                                            it.setImageResource(R.mipmap.icon_order22)
                                        }

                                        "ali" -> {
                                            it.visible()
                                            it.setImageResource(R.mipmap.icon_order26)
                                        }

                                        else -> it.gone()
                                    }
                                }

                                with<ImageView>(R.id.item_order_img_status) {
                                    it.isVisible = bean.hopeDate.isNotEmpty()

                                    bean.hopeDate.notEmpty {
                                        it.setImageResource(
                                            conditionIf(
                                                bean.fast,
                                                R.mipmap.icon_order07,
                                                R.mipmap.icon_order02
                                            )
                                        )
                                    }
                                }

                                clicked {
                                    startActivityEx<OrderDetailActivity>(
                                        "orderSn" to bean.orderSN,
                                        "shippingSn" to bean.shippingSn,
                                        "index" to bean.position
                                    )
                                }
                            }
                        }
                        .register<OrderFooter>(R.layout.item_order_list_foot) { jector, bean, _ ->
                            jector.apply {
                                text(R.id.item_order_count, bean.total_num)
                                text(R.id.item_order_total, bean.amount.formatDecimal())
                                text(R.id.item_order_total_hint, bean.amountHint)
                                text(R.id.item_order_name, bean.name)
                                text(R.id.item_order_phone, bean.phone)
                                text(R.id.item_order_addr, bean.address)
                                text(R.id.item_order_yu, bean.estimateDate)
                                text(R.id.item_order_cmemo, bean.cardMemo)
                                text(R.id.item_order_bmemo, bean.memo)

                                getView<View>(R.id.item_order_yu_ll)
                                    .isGone = bean.estimateDate.isEmpty()
                                getView<View>(R.id.item_order_cmemo_ll)
                                    .isGone = bean.cardMemo.isEmpty()
                                getView<View>(R.id.item_order_bmemo_ll)
                                    .isGone = bean.memo.isEmpty()

                                with<TextView>(R.id.item_order_pei) { tv ->
                                    tv.text =
                                        "配送员：${bean.adminName}${bean.adminPhone.ifNotEmpty { " - $it" }}"
                                    tv.isGone = bean.adminName.isEmpty()
                                }

                                with<TextView>(R.id.item_order_btn1) {
                                    it.text = bean.hint_btn1
                                    it.isGone =
                                        bean.status != "unpaid" || bean.hint_btn1.isEmpty()

                                    it.oneClick {
                                        when (bean.status) {
                                            "unpaid" ->
                                                startActivityEx<OrderConfirmActivity>(
                                                    "amount" to bean.amount.formatDecimal(),
                                                    "orderSn" to bean.orderSN,
                                                    "time" to bean.createDate,
                                                    "index" to bean.position
                                                )
                                        }
                                    }
                                }

                                with<TextView>(R.id.item_order_btn2) {
                                    it.text = bean.hint_btn2
                                    it.isGone =
                                        bean.status != "unpaid" || bean.hint_btn2.isEmpty()

                                    it.oneClick {
                                        when (bean.status) {
                                            "unpaid" -> updatePrice(
                                                bean.orderSN,
                                                bean.amount,
                                                bean.position
                                            )
                                        }
                                    }
                                }

                                with<TextView>(R.id.item_order_btn3) {
                                    it.text = bean.hint_btn3
                                    it.isGone =
                                        bean.status != "unpaid" || bean.hint_btn3.isEmpty()

                                    it.oneClick {
                                        when (bean.status) {
                                            "unpaid" -> cancelOrder(bean.orderSN, bean.position)
                                        }
                                    }
                                }

                                clicked {
                                    startActivityEx<OrderDetailActivity>(
                                        "orderSn" to bean.orderSN,
                                        "shippingSn" to bean.shippingSn,
                                        "index" to bean.position
                                    )
                                }
                            }
                        }
                        .attachTo(layout)
                }
            }
    }

    private fun initSearch() {
        mBinding
            .searchLayout
            .apply {
                searchEdit.hint = "请输入收货人、电话、地址"
                searchEdit.doOnTextChanged { text, _, _, _ ->
                    text?.let {
                        searchClose.isGone = it.isEmpty()

                        (it.isEmpty()
                                && mKeyWord.isNotEmpty())
                            .condition {
                                mKeyWord = ""
                                updateList()
                            }
                    }
                }

                searchEdit.setOnEditorActionListener { _, actionId, _ ->
                    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                        hideSoftInput() //隐藏软键盘

                        searchEdit
                            .text
                            .isBlank()
                            .conditionElse(
                                actionTrue = { showToast("请输入收货人、电话、地址") },
                                actionFalse = {
                                    mKeyWord = searchEdit.textTrim
                                    updateList()
                                }
                            )
                    }
                    return@setOnEditorActionListener false
                }

                searchClose.oneClick { searchEdit.setText("") }
                searchHint.oneClick {
                    searchEdit
                        .text
                        .isBlank()
                        .conditionElse(
                            actionTrue = { showToast("请输入收货人、电话、地址") },
                            actionFalse = {
                                mKeyWord = searchEdit.textTrim
                                updateList()
                            }
                        )
                }
            }
    }

    override fun initListener() {
        // 观察订单按钮操作
        observe<String>("orderList") { updateList() }
    }

    /**
     * 订单改价
     */
    private fun updatePrice(orderSN: String, amount: String, index: Int) {
        showPriceDialog(
            title = "订单改价",
            default = amount,
            onSure = { value ->
                getViewModel()
                    .updateOrder(orderSN, value)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("订单改价成功！")

                            val item = mList.find {
                                it is OrderFooter
                                        && it.position == index
                            } as OrderFooter

                            item.amount = value

                            mAdapter.notifyDataSetChanged()
                        }
                    )
            }
        )
    }

    /**
     * 取消订单
     */
    private fun cancelOrder(orderSN: String, index: Int) {
        showHintDialog(
            title = "取消订单",
            hint = "确定要取消订单吗？",
            onSure = {
                getViewModel()
                    .operateOrder(BaseUrl.orderCancel, orderSN)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("取消订单成功！")

                            mList.removeAll {
                                (it is OrderHeader && it.position == index)
                                        || (it is OrderGoods && it.position == index)
                                        || (it is OrderFooter && it.position == index)
                            }

                            mAdapter.notifyDataSetChanged()

                            mBinding.listLayout
                                .emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                    )
            }
        )
    }

    /**
     * 获取列表数据
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .orderList(
                page = index,
                state = "",
                roleId = userRole,
                keyWord = mKeyWord,
                onSuccess = {
                    mList.apply {
                        (index == 0)
                            .condition {
                                clear()
                                pageNum = 0
                            }

                        addItems(it)
                        it.notEmpty { pageNum++ }
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}